using Unity.Burst;
using Unity.Burst.Intrinsics;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace DOTS.DOD.LESSON7
{
    [BurstCompile]
    struct StopCubesRotateChunkJob : IJobChunk
    {
        [ReadOnly] public float DeltaTime;
        [ReadOnly] public float ElapsedTime;
        [ReadOnly] public float2 LeftRightBound;
        public ComponentTypeHandle<LocalTransform> TransformTypeHandle;
        public ComponentTypeHandle<RotateSpeed> RotateSpeedTypeHandle;

        public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask,
            in v128 chunkEnabledMask)
        {
            var chunkTransforms = chunk.GetNativeArray(ref TransformTypeHandle);
            var chunkRotateSpeeds = chunk.GetNativeArray(ref RotateSpeedTypeHandle);
            var enumerator = new ChunkEntityEnumerator(useEnabledMask, chunkEnabledMask, chunk.Count);
            while (enumerator.NextEntityIndex(out var i))
            {
                bool enabled = chunk.IsComponentEnabled(ref RotateSpeedTypeHandle, i);
                if (enabled) //启用旋转
                {
                    //在范围内的禁用旋转
                    if (chunkTransforms[i].Position.x >= LeftRightBound.x &&
                        chunkTransforms[i].Position.x <= LeftRightBound.y)
                    {
                        chunk.SetComponentEnabled(ref RotateSpeedTypeHandle, i, false);
                    }
                    else //范围外的执行旋转
                    {
                        var rotateSpeed = chunkRotateSpeeds[i];
                        chunkTransforms[i] = chunkTransforms[i].RotateY(rotateSpeed.Value * DeltaTime);
                    }
                }
                else //禁用旋转
                {
                    //在范围外的启用旋转
                    if (chunkTransforms[i].Position.x < LeftRightBound.x ||
                        chunkTransforms[i].Position.x > LeftRightBound.y)
                    {
                        chunk.SetComponentEnabled(ref RotateSpeedTypeHandle, i, true);
                        //恢复Scale
                        var trans = chunkTransforms[i];
                        trans.Scale = 1f;
                        chunkTransforms[i] = trans;
                    }
                    else //范围内的进行缩放
                    {
                        var trans = chunkTransforms[i];
                        trans.Scale = math.sin(ElapsedTime * 4) * 0.75f + 1f;
                        chunkTransforms[i] = trans;
                    }
                }
            }
        }
    }
}